package com.chenbei.common.util;

import cn.hutool.core.util.StrUtil;
import com.chenbei.common.enums.FileSizeUnitEnum;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class FileUtil {

    // 支持的图片文件扩展名
    private static final List<String> SUPPORTED_IMAGE_EXTENSIONS = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff"
    );

    // 常用大小单位对应的字节数
    private static final long KB = 1024;
    private static final long MB = KB * 1024;
    private static final long GB = MB * 1024;
    private static final long TB = GB * 1024;

    /**
     * 是否是图片类型的文件
     * @param file 文件
     * @return Boolean
     */
    public static Boolean isImage(MultipartFile file) {
        return isImageByExtension(file.getOriginalFilename());
    }

    public static Boolean isImageByExtension(String file) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        String fileExtension = getFileExtension(file).toLowerCase();
        return SUPPORTED_IMAGE_EXTENSIONS.contains(fileExtension);
    }

    /**
     * 检测文件大小
     * @param file 文件
     * @param maxSizeInBytes 最大字节数
     * @return Boolean
     */
    public static Boolean checkFileSize(MultipartFile file, long maxSizeInBytes) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        return file.getSize() <= maxSizeInBytes;
    }

    /**
     * 检测文件大小
     * @param file 文件
     * @param maxSize 最大大小
     * @param fileSizeUnitEnum 大小单位枚举
     * @return Boolean
     */
    public static Boolean checkFileSize(MultipartFile file, long maxSize, FileSizeUnitEnum fileSizeUnitEnum) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        long maxSizeInByte = 0;
        if (fileSizeUnitEnum.getUnit().equals(FileSizeUnitEnum.BYTE.getUnit())) {
            maxSizeInByte = maxSize;
        }
        if (fileSizeUnitEnum.getUnit().equals(FileSizeUnitEnum.KB.getUnit())) {
            maxSizeInByte = KB * maxSize;
        }
        if (fileSizeUnitEnum.getUnit().equals(FileSizeUnitEnum.MB.getUnit())) {
            maxSizeInByte = MB * maxSize;
        }
        if (fileSizeUnitEnum.getUnit().equals(FileSizeUnitEnum.GB.getUnit())) {
            maxSizeInByte = GB * maxSize;
        }

        return file.getSize() <= maxSizeInByte;
    }

    private static String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1);
    }
}
